angular.module('ProductStream')
    .controller('ProductStream.ProductStreamCtrl', ['$q', '$scope', '$state', '$stateParams', '$timeout', '$ionicLoading', '$ionicScrollDelegate', '$ionicPopup', 'Http', 'imanDialog', 'imanUsbPort', 'DevicePort',
        function($q, $scope, $state, $stateParams, $timeout, $ionicLoading, $ionicScrollDelegate, $ionicPopup, Http, imanDialog, imanUsbPort, DevicePort) {
            $scope.data = {
                basicInfo: {},
                bizCatalog: [],
                bizRecords: {
                    record: []
                },
                Barcode: '',
                icon_position: {}
            };


            function getQcInfo(Barcode) {
                queryProduct(Barcode).then(function(ref) {
                    angular.forEach(ref.bizCatalog, function(value) {
                        value.record = ref.bizRecords[value.UniqueId];
                        angular.forEach(value.record, function(rec) {
                            var uString = '';
                            angular.forEach(rec.Users, function(u) {
                                uString = uString + u.Name + ' ';
                            });
                            rec.Users = [{ Name: uString }];
                            rec.CollectDateTime = dateFormat(rec.CollectDateTime, "yyyy-MM-dd hh:mm:ss");
                            if (!rec.QCFlag && rec.WorkTime) {
                                var m = rec.WorkTime % 60;
                                var h = (rec.WorkTime - m) / 60;
                                rec.WorkTime = h + '小时' + parseInt(m) + '分钟';
                            }
                        });
                    });
                    if (ref.basicInfo.StartDateTime) {
                        ref.basicInfo.StartDateTime = dateFormat(ref.basicInfo.StartDateTime, "yyyy-MM-dd hh:mm:ss");
                    }
                    if (ref.basicInfo.RealStartDateTime) {
                        ref.basicInfo.RealStartDateTime = dateFormat(ref.basicInfo.RealStartDateTime, "yyyy-MM-dd hh:mm:ss");
                    }
                    if (ref.basicInfo.EndDateTime) {
                        ref.basicInfo.EndDateTime = dateFormat(ref.basicInfo.EndDateTime, "yyyy-MM-dd hh:mm:ss");
                    }

                    if (ref.basicInfo.RealEndDateTime) {
                        ref.basicInfo.RealEndDateTime = dateFormat(ref.basicInfo.RealEndDateTime, "yyyy-MM-dd hh:mm:ss");
                    }

                    $scope.data = {
                        basicInfo: ref.basicInfo,
                        bizCatalog: ref.bizCatalog,
                        bizRecords: ref.bizRecords,
                        productParam: ref.productParam,
                        Barcode: Barcode

                    };
                });
            }

            $scope.$on('$ionicView.beforeLeave', function() {
                DevicePort.close();
            });
            $scope.$on('$ionicView.afterEnter', function() {
                //imanUsbPort.start();
                DevicePort.open({
                    device: 0,
                    baudrate: 115200,
                    parseFn: true
                }).then(function() {
                    //imanDialog.toastBottom("成功");
                }, function(err) {
                    imanDialog.toastBottom("端口打开失败");
                });
            });
            $scope.$on('devicePort.DataReceived', function (e, barcode) {
                $scope.data.Barcode = barcode;
                getQcInfo(barcode);
            });

            function queryProduct(Barcode) {
                var defer = $q.defer();
                $ionicLoading.show();
                Http.post({
                    url: '/api/ProductFlow/getProductFlow',
                    data: {
                        Parameter: {
                            Barcode: Barcode
                        }
                    }
                }).then(function(result) {
                    defer.resolve(result);
                }, function(error) {
                    defer.reject(error);
                })['finally'](function() {
                    $ionicLoading.hide();
                });
                return defer.promise;
            }

            $scope.search = function(Barcode) {
                if (!Barcode) {
                    return;
                }
                $scope.data.Barcode = Barcode;
                getQcInfo(Barcode);
            };

            $scope.init = function() {
                $scope.search($stateParams.Barcode);
            };
            $scope.init();

            $scope.unfold = function(index) {
                var h = 0;
                for (var i = 0; i < index; i++) {
                    h += (angular.element('.list-exp_' + i).outerHeight() - 34);
                }
                $ionicScrollDelegate.scrollTo(0, h, false);
            };

            $scope.isScrolling = function() {
                for (var i = 0; i < $scope.data.bizCatalog.length + 2; i++) {
                    var show_top = angular.element('.list-exp_' + i).offset().top,
                        hide_top = 127 + i * 40;
                    if (show_top <= hide_top) {
                        angular.element('.list-icon-fix_' + i).removeClass('list-icon-hide');
                        angular.element('.list-icon_' + i).addClass('list-icon-show list-icon-hide-cursor');

                        for (var j = 0; j < i; j++) {
                            angular.element('.list-icon_' + j).removeClass('list-icon-show');
                        }
                        angular.element('.exp_' + i).addClass('list-icon-hide');
                    } else {
                        angular.element('.exp_' + i).removeClass('list-icon-hide');
                        angular.element('.list-icon_' + i).removeClass('list-icon-show list-icon-hide-cursor');
                        angular.element('.list-icon-fix_' + i).addClass('list-icon-hide');
                    }
                }
            };

            function dateFormat(dateStr, fmt) { //author: meizz 
                var date = new Date(dateStr);
                var o = {
                    "M+": date.getMonth() + 1, //月份   
                    "d+": date.getDate(), //日   
                    "h+": date.getHours(), //小时   
                    "m+": date.getMinutes(), //分   
                    "s+": date.getSeconds(), //秒   
                    "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
                    "S": date.getMilliseconds() //毫秒   
                };
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(fmt)) {
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    }
                }
                return fmt;
            }
        }
    ]);
